/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable react-native/no-inline-styles */
import React, {useState, useRef, memo} from 'react';
import {FlatList, RefreshControl} from 'react-native';
import {View, Colors, Image, Text} from 'react-native-ui-lib';
import {useScrollToTop} from '@react-navigation/native';
import CardItem from '../CardItem';
import {useNavigation} from '@react-navigation/native';
import Actions from '../Actions';

const List = ({refreshAsync, loading, data, listRef, head, stepList}) => {
  const flatListRef = listRef ?? useRef();
  useScrollToTop(flatListRef);
  const [refreshing, setRefreshing] = useState(false);
  const navigation = useNavigation();

  const onRefresh = async () => {
    // 下拉刷新
    setRefreshing(true);
    await refreshAsync();
    setRefreshing(false);
  };
  const [action, setAction] = useState({
    visible: false,
    onDismiss: () => {
      setAction(s => ({
        ...s,
        visible: false,
      }));
    },
  });
  return (
    <View flex-1>
      <Actions action={action} setAction={setAction} />
      {data?.length === 0 && (
        <View
          padding-10
          paddingH-16
          margin-10
          borderRadius={8}
          row
          centerV
          gap={12}
          backgroundColor={Colors.colorBgSecondary}>
          <Image
            source={require('../../assets/nodata.png')}
            aspectRatio={1}
            style={{
              borderRadius: 8,
              width: 66,
              height: 66,
              borderColor: Colors.colorCardBg,
              overflow: 'hidden',
              backgroundColor: 'transparent',
              marginLeft: 0,
            }}
          />
          <Text subheading flex-1>
            暂无数据
          </Text>
        </View>
      )}
      <FlatList
        ref={flatListRef}
        style={{paddingBottom: 66}}
        data={data}
        renderItem={({item}) =>
          CardItem({
            item,
            navigation,
            refreshAsync,
            head,
            stepList,
            action,
            setAction,
          })
        }
        keyExtractor={item => item.id.toString()}
        refreshControl={
          <RefreshControl
            refreshing={refreshing || loading}
            onRefresh={onRefresh}
          />
        }
      />
    </View>
  );
};

export default memo(List);
